#!/bin/bash
. /usr/share/Modules/init/bash
module load abinit/9.6.2
echo "Applying module abinit/9.6.2"
echo "Your mpi is $(which mpirun)"
echo "Your abinit is $(which abinit)"
for key in "$@"; do
  case $key in  
    --input_dir=*)  
      input_dir="${key#*=}"
      shift # past argument=value  
      ;;  
    --output_dir=*)  
      output_dir="${key#*=}"
      shift # past argument=value 
      ;;  
    --default)  
      DEFAULT=YES  
      shift # past argument with no value  
      ;;  
    *)
      ;;
  esac
done
if [ -z $input_dir ] || [ ! -d $input_dir ]; then
  echo "input error"
  exit 1
fi

if [ -z $output_dir ]; then
  echo "please input valid output_dir!"
  exit 1
fi

input_dir=${input_dir%*/}
output_dir=${output_dir%*/}
mkdir -p $output_dir
cd $input_dir

output_name=$(sed -n 2p ./files)
output_name=${output_name%*/}

echo "Your input directory is $input_dir"
echo "Your output directory is $output_dir"
echo "The number of tasks is $SLURM_NTASKS"
startTime_s=`date +%s`
startTime=`date +%Y%m%d-%H:%M:%S`
# ulimit -a &> log
# ulimit -s unlimited 
# ulimit -n unlimited 
# ulimit -l unlimited
mpirun -n $SLURM_NTASKS abinit<*.files>log.txt
execute_result=$?
if [ $execute_result -ne 0  ]; then
    echo "ABINIT fails, the result is $execute_result"
    exit $execute_result
fi
echo "ABINIT succeeds, the input dir : $input_dir, you can find the result in the dir: $output_dir"
endTime_s=`date +%s`
endTime=`date +%Y%m%d-%H:%M:%S`
sumTime=$[ $endTime_s - $startTime_s ]

echo "complete abinit calculation; $startTime ---> $endTime" "Total:$sumTime seconds"
mv $output_name $output_dir
mv log.txt $output_dir
